<script lang="ts" setup>
import type { Recordable } from '@vben/types';

import { onMounted, ref, unref } from 'vue';
import { useRoute } from 'vue-router';

import { useTabs } from '@vben/hooks';

import { useFs } from '@fast-crud/fast-crud';
import { Button } from 'ant-design-vue';

import { ExtendMsgApi, ExtendMsgConfig } from '#/api/basic/msg/extendMsg';
import { getValidateRulesByFs } from '#/api/common/validateByFs';
import { ActionEnum } from '#/enums/commonEnum';
import { useMessage } from '#/hooks/web/useMessage';
import { $t } from '#/locales';

import { createCrudOptions, frontRules } from './data/crud';

defineOptions({
  name: '消息管理编辑',
  inheritAttrs: false,
});
const { crudBinding, appendCrudOptions } = useFs({ createCrudOptions });

const type = ref<
  ActionEnum.ADD | ActionEnum.COPY | ActionEnum.EDIT | ActionEnum.VIEW
>(ActionEnum.ADD);
const typeFormRef = ref<
  ActionEnum.ADD | ActionEnum.COPY | ActionEnum.EDIT | ActionEnum.VIEW
>(ActionEnum.ADD);
const formRef = ref();
const buttonLoading = ref(false);
const { closeCurrentTab } = useTabs();
const { createMessage } = useMessage();
const route = useRoute();

async function formSubmit() {
  try {
    // buttonLoading.value = true;

    await formRef.value.submit();
    createMessage.success($t(`common.tips.${type.value}Success`));
    closeCurrentTab();
  } finally {
    buttonLoading.value = false;
  }
}

const load = async (data: Recordable) => {
  type.value = data?.type;
  typeFormRef.value = data?.type;

  if ([ActionEnum.COPY].includes(unref(type))) {
    typeFormRef.value = ActionEnum.ADD;
  }

  if (![ActionEnum.ADD].includes(unref(type))) {
    const record = await ExtendMsgApi.get(data?.id);
    record.id = undefined;
    formRef.value.setFormData(record, { mergeForm: false });
  }

  if (unref(type) !== ActionEnum.VIEW) {
    const validateApi = ExtendMsgConfig.Publish;
    const formOptions = await getValidateRulesByFs({
      Api: validateApi,
      mode: unref(type),
      customRules: frontRules(),
    });
    appendCrudOptions({ ...formOptions });
  }
};

onMounted(async () => {
  const { params } = route;
  load({ type: params?.type, id: params?.id });
});
</script>

<template>
  <FsPage>
    <template #header>
      <div class="title">发布消息</div>
    </template>
    <div class="bg-card p-5">
      <FsForm ref="formRef" v-bind="crudBinding[`${typeFormRef}Form`]" />
      <div style="margin-top: 10px">
        <Button
          v-if="formRef && type !== ActionEnum.VIEW"
          :loading="buttonLoading"
          @click="formSubmit"
        >
          立即发送
        </Button>
      </div>
    </div>
  </FsPage>
</template>
